'use strict';

angular.module('app.yksensor').directive('jqSensorGrid', function ($compile) {
    var jqGridCounter = 0;

    return {
        replace: true,
        restrict: 'E',
        scope: {
            gridData: '='
        },
        template: '<div>' +
            '<table></table>' +
            '<div class="jqgrid-pagination"></div>' +
            '</div>',
        controller: function($scope, $element,SensorService,$stateParams,HttpService){

            // 修改数据
            $scope.editRow  = function(row){
                // $element.find('table').editRow(row,true);
                console.log($element.find('table').editRow(row));

            };
            console.log($element.find('table').find('.jqgrid_new_role'));
                

            $scope.saveRow  = function(row){
                console.log("ok");
                console.log($element.find('table').find('.jqgrid_new_role'));
                console.log(row);
                $element.find('table').saveRow(row);
                // 保存修改的数据
                var table = $element.find('table');
                var current_tr = table.find('#'+row).attr('editable','0');
                var oldName1 = table.find('#'+row+'_label').parent().attr("title");
                var newName1 = table.find('input[name=label]').val();
                var newLength1 = table.find('input[name=length]').val();
                // var newProtocol_id1 = table.find('input[name=protocol_id]').val();
                var newType1 = table.find('input[name=type]').val();
                var field = { oldName: oldName1, newName: newName1, type: 'TEXT' };
                var protocolCon1 = {'label':newName1,'length':newLength1,'type':newType1};
                // console.log(oldName1);
                // console.log(newName1);
                var tableName = 'protocol' + $stateParams.protocolid;
                var data = { protocolCon: protocolCon1, field: field };
                console.log(data);
                SensorService.updateProtocolCon(tableName, data).then(function (response) {
                    if (response > 0) {
                        // GetData();
                        $.smallBox({
                            title: "编辑协议成功",
                            content: "<i class='fa fa-clock-o'></i> <i>编辑协议成功</i>",
                            color: "#659265",
                            iconSmall: "fa fa-check fa-2x fadeInRight animated",
                            timeout: 4000
                        });
                    }
                    else {

                    }

                })
                // 增加数据
                // console.log(row);
                
                // var field2 = { fieldName: $scope.sensorProtocol.label, type: 'TEXT' };
                // var data2 = {protocolCon:$scope.sensorProtocol,field:field2};
                // SensorService.addProtocolCon(tableName,data2).then(function (response) {
                //     if (response > 0) {
                //         // GetData();
                      
                //         $.smallBox({
                //             title: "添加协议成功",
                //             content: "<i class='fa fa-clock-o'></i> <i>添加协议成功</i>",
                //             color: "#659265",
                //             iconSmall: "fa fa-check fa-2x fadeInRight animated",
                //             timeout: 4000
                //         });
                //     }
                //     else {

                //     }

                // })

            };
             // console.log($scope.gridData.data);
             
             // var GetData = function () {

             //     var getWhereCon = { protocol_id: $stateParams.protocolid };

             //     return HttpService.Crud('query', getWhereCon, 'sensor_protocol_content');

             // }
             // GetData();
             //删除数据
            $scope.restoreRow  = function(row){
                // $element.find('table').restoreRow(row,true);
                // console.log($element.find('table').jqGrid());
                var table = $element.find('table');
                var rowData = $element.find('table').jqGrid('getRowData',row);
                var name = rowData.label;
                var tableName = 'protocol' + $stateParams.protocolid;
                var id = row.toString();
                var data = {'id':id,'name':name};
                console.log(data);
                // console.log($element.find('table').restoreRow(row));
                console.log(row);
                var current_tr = table.find('#'+row).remove();
                console.log(table.jqGrid('delRowData',row));
                SensorService.delProtocolCon('sensor_protocol_content', data).then(function (response) {
	            if (response > 0) {	                	               
	                $.smallBox({
	                    title: "删除协议成功",
	                    content: "<i class='fa fa-clock-o'></i> <i>删除协议成功</i>",
	                    color: "#659265",
	                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
	                    timeout: 4000
	                });
	
	            }
	            else {
	
	            }
	
	        })


            };

            // 
            // console.log($element.find('table').jqGrid('getRowData',row));
        },
        link: function (scope, element) {
            var gridNumber = jqGridCounter++;
            var wrapperId = 'jqgrid-' + gridNumber;
            element.attr('id', wrapperId);

            var tableId = 'jqgrid-table-' + gridNumber;
            var table = element.find('table');
            table.attr('id', tableId);

            var pagerId = 'jqgrid-pager-' + gridNumber;
            element.find('.jqgrid-pagination').attr('id', pagerId);


            table.jqGrid({
                data : scope.gridData.data,
                datatype : "local",
                height : 'auto',
                colNames : scope.gridData.colNames || [],
                colModel : scope.gridData.colModel || [],
                rowNum : 10,
                rowList : [10, 20, 30],
                pager : '#' + pagerId,
                sortname : 'id',
                toolbarfilter : true,
                viewrecords : true,
                sortorder : "asc",
                gridComplete : function() {
                    var ids = table.jqGrid('getDataIDs');
                    console.log(ids);
                    for (var i = 0; i < ids.length; i++) {
                        var cl = ids[i];
                        var be = "<button class='btn btn-xs btn-default' uib-tooltip='Edit Row' tooltip-append-to-body='true' ng-click='editRow("+ cl + ")'><i class='fa fa-pencil'></i></button>";

                        var se = "<button class='btn btn-xs btn-default' uib-tooltip='Save Row' tooltip-append-to-body='true' ng-click='saveRow("+ cl + ")'><i class='fa fa-save'></i></button>";
                        
//                      var ca = "<button class='btn btn-xs btn-default' uib-tooltip='Cancel' tooltip-append-to-body='true' ng-click='restoreRow("+ name + ")'><i class='fa fa-times'></i></button>";
                        var ca = "<button class='btn btn-xs btn-default' uib-tooltip='Cancel' tooltip-append-to-body='true' ng-click='restoreRow("+ cl + ")'><i class='fa fa-times'></i></button>";
                         // console.log(se);

                        
                        table.jqGrid('setRowData', ids[i], {
                            act : be + se + ca
                        });
                    }
                },
                onSelectRow:function(ids){
                   var rowData = table.jqGrid("getRowData",ids);

                   // console.log(rowData);

                },
                editurl : "dummy.html",
                caption : "SmartAdmin jQgrid Skin",
                multiselect : true,
                autowidth : true

            });
            table.jqGrid('navGrid', '#' + pagerId, {
                edit : true,
                add : true,
                del : true
            });
            table.jqGrid('inlineNav', '#' + pagerId);


            element.find(".ui-jqgrid").removeClass("ui-widget ui-widget-content");
            element.find(".ui-jqgrid-view").children().removeClass("ui-widget-header ui-state-default");
            element.find(".ui-jqgrid-labels, .ui-search-toolbar").children().removeClass("ui-state-default ui-th-column ui-th-ltr");
            element.find(".ui-jqgrid-pager").removeClass("ui-state-default");
            element.find(".ui-jqgrid").removeClass("ui-widget-content");

            // add classes
            element.find(".ui-jqgrid-htable").addClass("table table-bordered table-hover");
            element.find(".ui-jqgrid-btable").addClass("table table-bordered table-striped");

            element.find(".ui-pg-div").removeClass().addClass("btn btn-sm btn-primary");
            element.find(".ui-icon.ui-icon-plus").removeClass().addClass("fa fa-plus");
            element.find(".ui-icon.ui-icon-pencil").removeClass().addClass("fa fa-pencil");
            element.find(".ui-icon.ui-icon-trash").removeClass().addClass("fa fa-trash-o");
            element.find(".ui-icon.ui-icon-search").removeClass().addClass("fa fa-search");
            element.find(".ui-icon.ui-icon-refresh").removeClass().addClass("fa fa-refresh");
            element.find(".ui-icon.ui-icon-disk").removeClass().addClass("fa fa-save").parent(".btn-primary").removeClass("btn-primary").addClass("btn-success");
            element.find(".ui-icon.ui-icon-cancel").removeClass().addClass("fa fa-times").parent(".btn-primary").removeClass("btn-primary").addClass("btn-danger");

            element.find(".ui-icon.ui-icon-seek-prev").wrap("<div class='btn btn-sm btn-default'></div>");
            element.find(".ui-icon.ui-icon-seek-prev").removeClass().addClass("fa fa-backward");

            element.find(".ui-icon.ui-icon-seek-first").wrap("<div class='btn btn-sm btn-default'></div>");
            element.find(".ui-icon.ui-icon-seek-first").removeClass().addClass("fa fa-fast-backward");

            element.find(".ui-icon.ui-icon-seek-next").wrap("<div class='btn btn-sm btn-default'></div>");
            element.find(".ui-icon.ui-icon-seek-next").removeClass().addClass("fa fa-forward");

            element.find(".ui-icon.ui-icon-seek-end").wrap("<div class='btn btn-sm btn-default'></div>");
            element.find(".ui-icon.ui-icon-seek-end").removeClass().addClass("fa fa-fast-forward");

            $(window).on('resize.jqGrid', function() {
               table.jqGrid('setGridWidth', $("#content").width());
            });

            $compile(element.contents())(scope);
        }
    }
});